package com.monai.aidati.biMq;

import com.monai.aidati.aiservice.ChatCompletionsExample;
import com.monai.aidati.common.ErrorCode;
import com.monai.aidati.exception.BusinessException;
import com.monai.aidati.model.entity.Chart;
import com.monai.aidati.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class BiMessageConsumer {
    @Autowired
    private ChartService chartService;


    @RabbitListener(queues = {"bi_queue"},ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)long deliveryTag) throws IOException {
        Long chartId=Long.parseLong(message);
        if(StringUtils.isBlank(message)){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        Chart chart=chartService.getById(chartId);
        if(chart==null){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "未能查询到当前表格信息"+chartId);
        }
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }

        String userInput=buildUserInput(chart);
        String result=ChatCompletionsExample.run(userInput);
        // 初始化 String[] 数组
        String[] splits = new String[4];
        // 找到各部分的分割点
        int firstBrace = result.indexOf("{");
        int lastBrace = result.lastIndexOf("}");
        int conclusionIndex = result.indexOf("结论：");
        // 分割并存储到数组中
        splits[0] = result.substring(0, result.indexOf("=") + 1).trim(); // 第一部分
        splits[1] = result.substring(firstBrace, lastBrace + 1).trim(); // 第二部分
        splits[2] = result.substring(lastBrace + 1, conclusionIndex).trim(); // 第三部分
        if(!StringUtils.isBlank(result.substring(conclusionIndex).trim())){
            splits[3] = result.substring(conclusionIndex).trim(); // 第四部分
        }
        String genChart=splits[1];
        String genResult=splits[3];
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
// todo 建议定义状态为枚举值
        updateChartResult.setStatus("succeed");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }
        // 消息确认
        channel.basicAck(deliveryTag, false);
    }
    /**
     * 构建用户输入
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        return userInput.toString();
    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage("execMessage");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }
}
